package uns.fit.gis.ui;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.microedition.lcdui.ChoiceGroup;
import javax.microedition.lcdui.Command;
import javax.microedition.lcdui.CommandListener;
import javax.microedition.lcdui.Displayable;
import javax.microedition.lcdui.Form;
import javax.microedition.lcdui.TextField;
import javax.microedition.media.Manager;
import javax.microedition.media.Player;
import javax.microedition.media.PlayerListener;
import javax.microedition.media.control.RecordControl;

import uns.fit.gis.MapDrawer;
import uns.fit.gis.audio.PlayerThread;
import uns.fit.gis.fileio.AudioData;
import uns.fit.gis.fileio.FileWrapper;

public class RecorderForm extends Form implements CommandListener,
		PlayerListener, Runnable {
	private MapDrawer midlet;
	private ByteArrayOutputStream outputStream = null;
	private byte[] byteArray = null;
	private String locator = "capture://audio?encoding=pcm";
	private Player player = null;
	private TextField tb = null;
	private Command recCommand, stopRecCommand, playCommand, backCommand;
	//private VolumeControl vc;
	private RecordControl rc = null;
	private ChoiceGroup cg;
	
	public RecorderForm(MapDrawer midlet) {
		super("");
		this.midlet = midlet;
		cg = new ChoiceGroup("Record to", ChoiceGroup.EXCLUSIVE);
		
		cg.append("byteArray", null);
		
		recCommand = new Command("Record", Command.OK, 1);
		stopRecCommand = new Command("Stop record", Command.OK, 1);
		playCommand = new Command("Play", Command.SCREEN, 2);
		backCommand = new Command("Back", Command.SCREEN, 2);

		tb = new TextField("SoundCapture", "info", 256, TextField.UNEDITABLE);
		this.addCommand(recCommand);
		this.addCommand(playCommand);
		this.addCommand(backCommand);
		this.setCommandListener(this);

		this.append(tb);
		this.append(cg);
	}

	public void commandAction(Command c, Displayable s) {
		if (c == recCommand) // start the recording
		{
			Thread test = new Thread(this);
			test.start();

		} else if (c == stopRecCommand) // Stop the recording
		{
			System.out.println("StoprecCommand");
			// Changing the stopCommand with recCommand
			this.removeCommand(stopRecCommand);
			this.addCommand(recCommand);
			System.out.println("Recorded Data is ");
			try {

				// stop recording
				rc.commit();

				// and stop the playback from the microphone
				//vc.setMute(false);// to mute
				player.close();

				tb.setString("Recorder to byteArray stopped:");
				/*
				 * Test saving
				 */
				new Thread() {
					public void run() {
						byteArray = outputStream.toByteArray();
						AudioData audioData = new AudioData();
						audioData.setData(byteArray);
						String dirPhotos = System.getProperty("fileconn.dir.photos");
			            if(dirPhotos == null) {
			            	dirPhotos = "file:///root1/";
			            }
						StringBuffer strBuf = new StringBuffer();
						strBuf.append(dirPhotos);
						
						System.out.println(strBuf.toString());
						
						strBuf.append("GeoAudio");
						strBuf.append(System.currentTimeMillis());
						strBuf.append(".wav");
						FileWrapper.save(audioData, strBuf.toString());
					}
				}.start();
				
			} catch (Exception e) {
				tb.setString(e.toString());
			}
		} else if (c == playCommand) // start the playback of the recorded
										// audio
		{

			System.out.println("play from ByteArrayInputStream");

			if (outputStream == null)
				return;
			// getting the ByteArray from the ByteArrayOutputStream
			byteArray = outputStream.toByteArray();

			// Creating and starting the playback thread
			new PlayerThread(new ByteArrayInputStream(byteArray), "audio/X-wav")
					.start();
			tb.setString("Playing ");

		}

		else if (c == backCommand) {
			midlet.showMapCanvas();
		}

	}

	public void playerUpdate(Player player, java.lang.String event,
			java.lang.Object eventData) {
		System.out.println("playerUpdate event=" + event);

	}

	public void run() {
		System.out.println("recCommand");
		tb.setString("Recorder started:");
		// Changing the recCommand with the stopCommand
		this.removeCommand(recCommand);
		this.addCommand(stopRecCommand);

		try {
			// creating the player from the file url enabling progressive
			// download
			player = Manager.createPlayer(locator);
			// adding playerListenter
			player.addPlayerListener(this);
			// allocating the resources from the microphone
			player.realize();
			// Getting the ReocrdControll so we can record the output from the
			// player
			rc = (RecordControl) player.getControl("RecordControl");
			// rc.setRecordSizeLimit(60000);
		} catch (Exception er) {
			tb.setString(er.toString());
		}

		outputStream = null;
		outputStream = new ByteArrayOutputStream();

		if (rc == null)
			System.out.println("rc==null");
		// setting the record location to the outputstream
		else {
			rc.setRecordStream(outputStream);
	
			try {
				// start recording
				rc.startRecord();
				//vc = (VolumeControl) player.getControl("VolumeControl");
				
				// start to play the sound from the microphone
				//player.start();
				//vc.setMute(true);//to mute.
				
			} catch (Exception e) {
				tb.setString(e.toString());
			}
		}
	}
}
